socket = require("socket")
mooni2p = require("mooni2p")

-- SAM server and port (defaults are used if nil)
server = "127.0.0.1"
port = 7656

local session_name = "testserver"

-- generate a new I2P destination
local server_dest = assert(mooni2p.new_destination(server,port))
print(string.format("Listening at: %s.b32.i2p", server_dest:base32()))
print("Creating session, please wait...")

-- create SAM session with specified destination
local session_sock = assert(mooni2p.create_session(session_name, server_dest, server, port))
print("Session created.")

-- accept a peer from I2P
local sock = assert(mooni2p.stream_accept(session_name, server, port))
print("Accepting peers...")

-- when a peer is connected, the first line is his I2P destination
dest = mooni2p.Destination:new(sock:receive("*l"))
print("Peer connected:", dest:base32())

while 1 do
	-- receive data from a peer
	data = sock:receive("*l")
	if #data == 0 then
		print("connection closed\n")
		break
	else
		if string.find(data, "PING") then
			sock:send("PONG\n")
		elseif string.find(data, "STOP") then
			break
		end
	end
end

-- close connection with active peer
sock:close()
-- shutdown SAM session
session_sock:close()
